﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace MyFramework.Core
{
    /// <summary>
    /// extension methods
    /// </summary>
    public static class ExtensionMethods
    {
        /// <summary>
        /// Formats the executable.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public static string FormatEx(this string format, params object[] args)
        {
            return string.Format(CultureInfo.CurrentCulture, format, args);
        }

        /// <summary>
        /// Executes the when.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyChangedEnabledObject">The property changed enabled object.</param>
        /// <param name="propertyMatchEvaluator">The property match evaluator.</param>
        /// <param name="actionToExecute">The action automatic execute.</param>
        /// <param name="executeOnce">if set to <c>true</c> [execute once].</param>
        public static void ExecuteWhen<T>(this T propertyChangedEnabledObject, Func<string, T, bool> propertyMatchEvaluator, Action<T> actionToExecute, bool executeOnce) where T : INotifyPropertyChanged
        {
            PropertyChangedEventHandler fn = null;
            fn = (s, e) =>
            {
                if (propertyMatchEvaluator(e.PropertyName, propertyChangedEnabledObject))
                {
                    actionToExecute(propertyChangedEnabledObject);

                    if (executeOnce)
                    {
                        propertyChangedEnabledObject.PropertyChanged -= fn;
                    }
                }
            };

            propertyChangedEnabledObject.PropertyChanged += fn;
        }
    }
}
